/**
 * 检测数据库表格中天赋石基础数据是否正确
 * 对比文档中的数据和数据库中的实际数据
 */

const mysql = require('mysql2/promise');
const config = require('./database-config.js');

const dbConfig = config.source;

// 文档中的天赋石等级元气数据
const docLevelData = [
    { level: 1, energy: 100, silverCost: 0 },
    { level: 2, energy: 100, silverCost: 1000 },
    { level: 4, energy: 331, silverCost: 6000 },
    { level: 6, energy: 610, silverCost: 15000 },
    { level: 8, energy: 948, silverCost: 28000 },
    { level: 10, energy: 1357, silverCost: 45000 },
    { level: 12, energy: 1852, silverCost: 66000 },
    { level: 14, energy: 2451, silverCost: 91000 },
    { level: 16, energy: 3176, silverCost: 120000 },
    { level: 18, energy: 4053, silverCost: 153000 },
    { level: 20, energy: 5114, silverCost: 190000 },
    { level: 22, energy: 6344, silverCost: 231000 },
    { level: 24, energy: 7598, silverCost: 276000 },
    { level: 26, energy: 8877, silverCost: 325000 },
    { level: 28, energy: 10182, silverCost: 378000 },
    { level: 30, energy: 11513, silverCost: 435000 },
    { level: 32, energy: 12871, silverCost: 496000 },
    { level: 34, energy: 14256, silverCost: 561000 },
    { level: 36, energy: 15669, silverCost: 630000 },
    { level: 38, energy: 17110, silverCost: 703000 },
    { level: 40, energy: 18581, silverCost: 780000 },
    { level: 42, energy: 20081, silverCost: 861000 },
    { level: 44, energy: 21611, silverCost: 946000 },
    { level: 46, energy: 23172, silverCost: 1035000 },
    { level: 48, energy: 24764, silverCost: 1128000 },
    { level: 50, energy: 26388, silverCost: 1225000 },
    { level: 52, energy: 28045, silverCost: 1326000 },
    { level: 54, energy: 29735, silverCost: 1431000 },
    { level: 56, energy: 31459, silverCost: 1540000 },
    { level: 58, energy: 33218, silverCost: 1653000 },
    { level: 60, energy: 35013, silverCost: 1770000 },
    { level: 62, energy: 36844, silverCost: 1891000 },
    { level: 64, energy: 38711, silverCost: 2016000 },
    { level: 66, energy: 40616, silverCost: 2145000 },
    { level: 68, energy: 42559, silverCost: 2278000 },
    { level: 70, energy: 44541, silverCost: 2415000 },
    { level: 72, energy: 46563, silverCost: 2556000 },
    { level: 74, energy: 48625, silverCost: 2701000 },
    { level: 76, energy: 50729, silverCost: 2850000 },
    { level: 78, energy: 52875, silverCost: 3003000 },
    { level: 80, energy: 55064, silverCost: 3160000 },
    { level: 82, energy: 57297, silverCost: 3321000 },
    { level: 84, energy: 59575, silverCost: 3486000 },
    { level: 86, energy: 61899, silverCost: 3655000 },
    { level: 88, energy: 64269, silverCost: 3828000 },
    { level: 90, energy: 66687, silverCost: 4005000 },
    { level: 92, energy: 69154, silverCost: 4186000 },
    { level: 94, energy: 71671, silverCost: 4371000 },
    { level: 96, energy: 74238, silverCost: 4560000 },
    { level: 98, energy: 76857, silverCost: 4753000 },
    { level: 100, energy: 79528, silverCost: 4950000 },
    { level: 102, energy: 82375, silverCost: 5151000 },
    { level: 104, energy: 85819, silverCost: 5356000 },
    { level: 106, energy: 89987, silverCost: 5565000 },
    { level: 108, energy: 95031, silverCost: 5778000 },
    { level: 110, energy: 101134, silverCost: 5995000 },
    { level: 112, energy: 108518, silverCost: 6216000 },
    { level: 114, energy: 117453, silverCost: 6441000 },
    { level: 116, energy: 128264, silverCost: 6670000 },
    { level: 118, energy: 141346, silverCost: 6903000 },
    { level: 120, energy: 157175, silverCost: 7140000 },
    { level: 122, energy: 175508, silverCost: 7381000 },
    { level: 124, energy: 194209, silverCost: 7626000 },
    { level: 126, energy: 213286, silverCost: 7875000 },
    { level: 128, energy: 232747, silverCost: 8128000 },
    { level: 130, energy: 252598, silverCost: 8385000 },
    { level: 132, energy: 272849, silverCost: 8646000 },
    { level: 134, energy: 293506, silverCost: 8911000 },
    { level: 136, energy: 314579, silverCost: 9180000 },
    { level: 138, energy: 336076, silverCost: 9453000 },
    { level: 140, energy: 358005, silverCost: 9730000 },
    { level: 142, energy: 380374, silverCost: 10011000 },
    { level: 144, energy: 403193, silverCost: 10296000 },
    { level: 146, energy: 426471, silverCost: 10585000 },
    { level: 148, energy: 450217, silverCost: 10878000 },
    { level: 150, energy: 474440, silverCost: 11175000 },
    { level: 152, energy: 499149, silverCost: 11476000 },
    { level: 154, energy: 524354, silverCost: 11781000 },
    { level: 156, energy: 550066, silverCost: 12090000 },
    { level: 158, energy: 576296, silverCost: 12403000 },
    { level: 160, energy: 603053, silverCost: 12720000 }
];

// 文档中的天赋石基础配置数据
const docBaseData = [
    // 武士职业
    { typeId: 1, name: "舍命石", description: "提高致命威力", roleType: 1, baseEffect: 5.0, effectType: 1 },
    { typeId: 2, name: "强攻石", description: "提升攻击力", roleType: 1, baseEffect: 10.0, effectType: 1 },
    { typeId: 3, name: "舍攻石", description: "转化攻击力", roleType: 1, baseEffect: 20.0, effectType: 1 },
    { typeId: 4, name: "忽视石", description: "提高忽视几率", roleType: 1, baseEffect: 10.0, effectType: 1 },
    { typeId: 5, name: "暴击石", description: "提高暴击威力", roleType: 1, baseEffect: 25.0, effectType: 1 },
    { typeId: 6, name: "合击石", description: "提高合击几率", roleType: 1, baseEffect: 10.0, effectType: 1 },

    // 异人职业
    { typeId: 10, name: "法爆石", description: "提高法术暴击几率", roleType: 3, baseEffect: 4.5, effectType: 1 },
    { typeId: 11, name: "毒术石", description: "提升毒术威力", roleType: 3, baseEffect: 5.0, effectType: 1 },
    { typeId: 12, name: "风沙石", description: "提升风沙威力", roleType: 3, baseEffect: 5.0, effectType: 1 },
    { typeId: 13, name: "妖火石", description: "提升妖火威力", roleType: 3, baseEffect: 5.0, effectType: 1 },
    { typeId: 14, name: "落雷石", description: "提升落雷威力", roleType: 3, baseEffect: 5.0, effectType: 1 },

    // 文人职业
    { typeId: 15, name: "扰乱石", description: "提升扰乱威力", roleType: 2, baseEffect: 5.0, effectType: 1 },
    { typeId: 16, name: "封锁石", description: "提升封锁威力", roleType: 2, baseEffect: 5.0, effectType: 1 },
    { typeId: 17, name: "围困石", description: "提升围困威力", roleType: 2, baseEffect: 5.0, effectType: 1 },
    { typeId: 18, name: "暗渡石", description: "提升暗渡威力", roleType: 2, baseEffect: 5.0, effectType: 1 },
    { typeId: 19, name: "夺命石", description: "提升夺命程度", roleType: 2, baseEffect: 28.0, effectType: 1 },

    // 通用职业
    { typeId: 20, name: "强血石", description: "增加生命值", roleType: 0, baseEffect: 5.0, effectType: 1 },
    { typeId: 21, name: "反击石", description: "提高反击几率", roleType: 0, baseEffect: 10.0, effectType: 1 },
    { typeId: 22, name: "爆率石", description: "提高爆率", roleType: 0, baseEffect: 5.0, effectType: 1 },
    { typeId: 23, name: "致命石", description: "提高致命几率", roleType: 0, baseEffect: 10.0, effectType: 1 },
    { typeId: 24, name: "躲避石", description: "提高躲避几率", roleType: 0, baseEffect: 10.0, effectType: 1 }
];

class TalentStoneDataChecker {
    constructor() {
        this.connection = null;
        this.checkResults = {
            levelData: { correct: 0, incorrect: 0, missing: 0, extra: 0, errors: [] },
            baseData: { correct: 0, incorrect: 0, missing: 0, extra: 0, errors: [] }
        };
    }

    async runCheck() {
        try {
            console.log('🔍 开始检测天赋石基础数据...\n');

            // 连接数据库
            await this.connectDatabase();

            // 检查天赋石等级元气数据
            await this.checkLevelData();

            // 检查天赋石基础配置数据
            await this.checkBaseData();

            // 输出检查结果
            this.printResults();

        } catch (error) {
            console.error('❌ 检测过程中发生错误:', error.message);
        } finally {
            if (this.connection) {
                await this.connection.end();
            }
        }
    }

    async connectDatabase() {
        console.log('🔌 连接数据库...');
        this.connection = await mysql.createConnection(dbConfig);
        console.log('✅ 数据库连接成功\n');
    }

    async checkLevelData() {
        console.log('📊 检查天赋石等级元气数据...');

        try {
            // 查询数据库中的等级数据
            const [dbLevels] = await this.connection.execute(`
                SELECT level, energy, silver_cost 
                FROM talent_stone_level 
                ORDER BY level
            `);

            console.log(`数据库中有 ${dbLevels.length} 条等级数据`);
            console.log(`文档中有 ${docLevelData.length} 条等级数据\n`);

            // 创建数据库数据的映射
            const dbLevelMap = new Map();
            dbLevels.forEach(level => {
                dbLevelMap.set(level.level, {
                    energy: level.energy,
                    silverCost: level.silver_cost
                });
            });

            // 检查文档中的每个等级
            for (const docLevel of docLevelData) {
                const dbLevel = dbLevelMap.get(docLevel.level);

                if (!dbLevel) {
                    this.checkResults.levelData.missing++;
                    this.checkResults.levelData.errors.push(`❌ 等级 ${docLevel.level} 在数据库中不存在`);
                } else {
                    const energyMatch = dbLevel.energy === docLevel.energy;
                    const silverMatch = dbLevel.silverCost === docLevel.silverCost;

                    if (energyMatch && silverMatch) {
                        this.checkResults.levelData.correct++;
                        console.log(`✅ 等级 ${docLevel.level}: 元气=${docLevel.energy}, 消耗=${docLevel.silverCost} (正确)`);
                    } else {
                        this.checkResults.levelData.incorrect++;
                        const errors = [];
                        if (!energyMatch) errors.push(`元气值不匹配: 文档=${docLevel.energy}, 数据库=${dbLevel.energy}`);
                        if (!silverMatch) errors.push(`银两消耗不匹配: 文档=${docLevel.silverCost}, 数据库=${dbLevel.silverCost}`);

                        this.checkResults.levelData.errors.push(`❌ 等级 ${docLevel.level}: ${errors.join(', ')}`);
                        console.log(`❌ 等级 ${docLevel.level}: ${errors.join(', ')}`);
                    }
                }
            }

            // 检查数据库中多余的等级
            for (const dbLevel of dbLevels) {
                const docLevel = docLevelData.find(level => level.level === dbLevel.level);
                if (!docLevel) {
                    this.checkResults.levelData.extra++;
                    this.checkResults.levelData.errors.push(`⚠️ 等级 ${dbLevel.level} 在文档中不存在`);
                }
            }

        } catch (error) {
            console.error('❌ 检查等级数据时发生错误:', error.message);
            this.checkResults.levelData.errors.push(`❌ 检查等级数据时发生错误: ${error.message}`);
        }

        console.log('');
    }

    async checkBaseData() {
        console.log('💎 检查天赋石基础配置数据...');

        try {
            // 查询数据库中的基础配置数据
            const [dbBases] = await this.connection.execute(`
                SELECT type_id, name, description, role_type, base_effect, effect_type 
                FROM talent_stone_base 
                ORDER BY type_id
            `);

            console.log(`数据库中有 ${dbBases.length} 条基础配置数据`);
            console.log(`文档中有 ${docBaseData.length} 条基础配置数据\n`);

            // 创建数据库数据的映射
            const dbBaseMap = new Map();
            dbBases.forEach(base => {
                dbBaseMap.set(base.type_id, {
                    name: base.name,
                    description: base.description,
                    roleType: base.role_type,
                    baseEffect: parseFloat(base.base_effect),
                    effectType: base.effect_type
                });
            });

            // 检查文档中的每个基础配置
            for (const docBase of docBaseData) {
                const dbBase = dbBaseMap.get(docBase.typeId);

                if (!dbBase) {
                    this.checkResults.baseData.missing++;
                    this.checkResults.baseData.errors.push(`❌ 类型ID ${docBase.typeId} (${docBase.name}) 在数据库中不存在`);
                } else {
                    const nameMatch = dbBase.name === docBase.name;
                    const descMatch = dbBase.description === docBase.description;
                    const roleMatch = dbBase.roleType === docBase.roleType;
                    const effectMatch = Math.abs(dbBase.baseEffect - docBase.baseEffect) < 0.01;
                    const typeMatch = dbBase.effectType === docBase.effectType;

                    if (nameMatch && descMatch && roleMatch && effectMatch && typeMatch) {
                        this.checkResults.baseData.correct++;
                        console.log(`✅ 类型ID ${docBase.typeId} (${docBase.name}): 职业=${docBase.roleType}, 效果=${docBase.baseEffect}% (正确)`);
                    } else {
                        this.checkResults.baseData.incorrect++;
                        const errors = [];
                        if (!nameMatch) errors.push(`名称不匹配: 文档=${docBase.name}, 数据库=${dbBase.name}`);
                        if (!descMatch) errors.push(`描述不匹配: 文档=${docBase.description}, 数据库=${dbBase.description}`);
                        if (!roleMatch) errors.push(`职业不匹配: 文档=${docBase.roleType}, 数据库=${dbBase.roleType}`);
                        if (!effectMatch) errors.push(`效果不匹配: 文档=${docBase.baseEffect}, 数据库=${dbBase.baseEffect}`);
                        if (!typeMatch) errors.push(`类型不匹配: 文档=${docBase.effectType}, 数据库=${dbBase.effectType}`);

                        this.checkResults.baseData.errors.push(`❌ 类型ID ${docBase.typeId} (${docBase.name}): ${errors.join(', ')}`);
                        console.log(`❌ 类型ID ${docBase.typeId} (${docBase.name}): ${errors.join(', ')}`);
                    }
                }
            }

            // 检查数据库中多余的基础配置
            for (const dbBase of dbBases) {
                const docBase = docBaseData.find(base => base.typeId === dbBase.type_id);
                if (!docBase) {
                    this.checkResults.baseData.extra++;
                    this.checkResults.baseData.errors.push(`⚠️ 类型ID ${dbBase.type_id} (${dbBase.name}) 在文档中不存在`);
                }
            }

        } catch (error) {
            console.error('❌ 检查基础配置数据时发生错误:', error.message);
            this.checkResults.baseData.errors.push(`❌ 检查基础配置数据时发生错误: ${error.message}`);
        }

        console.log('');
    }

    printResults() {
        console.log('📋 检测结果汇总:');
        console.log('='.repeat(60));

        // 等级数据结果
        console.log('\n📊 天赋石等级元气数据:');
        console.log(`✅ 正确: ${this.checkResults.levelData.correct}`);
        console.log(`❌ 错误: ${this.checkResults.levelData.incorrect}`);
        console.log(`⚠️ 缺失: ${this.checkResults.levelData.missing}`);
        console.log(`➕ 多余: ${this.checkResults.levelData.extra}`);

        // 基础配置数据结果
        console.log('\n💎 天赋石基础配置数据:');
        console.log(`✅ 正确: ${this.checkResults.baseData.correct}`);
        console.log(`❌ 错误: ${this.checkResults.baseData.incorrect}`);
        console.log(`⚠️ 缺失: ${this.checkResults.baseData.missing}`);
        console.log(`➕ 多余: ${this.checkResults.baseData.extra}`);

        // 详细错误信息
        if (this.checkResults.levelData.errors.length > 0) {
            console.log('\n📊 等级数据详细错误:');
            this.checkResults.levelData.errors.forEach(error => console.log(`  ${error}`));
        }

        if (this.checkResults.baseData.errors.length > 0) {
            console.log('\n💎 基础配置数据详细错误:');
            this.checkResults.baseData.errors.forEach(error => console.log(`  ${error}`));
        }

        // 总体评估
        const totalCorrect = this.checkResults.levelData.correct + this.checkResults.baseData.correct;
        const totalIncorrect = this.checkResults.levelData.incorrect + this.checkResults.baseData.incorrect;
        const totalMissing = this.checkResults.levelData.missing + this.checkResults.baseData.missing;
        const totalExtra = this.checkResults.levelData.extra + this.checkResults.baseData.extra;

        console.log('\n🎯 总体评估:');
        console.log(`✅ 总正确数: ${totalCorrect}`);
        console.log(`❌ 总错误数: ${totalIncorrect}`);
        console.log(`⚠️ 总缺失数: ${totalMissing}`);
        console.log(`➕ 总多余数: ${totalExtra}`);

        if (totalIncorrect === 0 && totalMissing === 0 && totalExtra === 0) {
            console.log('\n🎉 所有数据都正确！');
        } else {
            console.log('\n⚠️ 发现数据问题，需要修复');
        }

        console.log('='.repeat(60));
    }
}

// 运行检测
async function main() {
    const checker = new TalentStoneDataChecker();
    await checker.runCheck();
}

// 如果直接运行此脚本
if (require.main === module) {
    main().catch((error) => {
        console.error('💥 检测脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = TalentStoneDataChecker;
